<!---
Permissions
Block archiving for user that has workshops, orders, funds
--->

<cfparam name="User_ID" type="integer" default="0" />
<cfparam name="returnView" type="string" default="users" />
<cfparam name="passback" type="string" default="" />

<cfscript>
	userGateway = new assets.calgrants.com.gateway.UserGateway();
	user = userGateway.get(User_ID = User_ID);
</cfscript>

<!--- <cfset canEdit = false />
<cfif IsUserInRole("Super User") OR user.getUser_ID() eq 0>
	<cfset canEdit = true />
<cfelseif IsUserInRole("Regional Admin")>
	<cfif user.getRole() eq "Regional Admin" AND user.getUser_ID() eq GetAuthUser()>
		<cfset canEdit = true />
	<!--- need to know what region user is in to do Regional Admin check --->
	<cfelseif ListFind("Organizer,Site Contact", user.getRole())>
	
	</cfif>
</cfif> --->

<!--- <cfif IsNumeric(user.getUser_ID()) AND
	(
		(IsUserInRole("Super User")) OR 
		(IsUserInRole("Regional Admin") AND user.getRole() neq "Super User" AND (user.getRole() neq "Regional Admin" OR user.getUser_ID() eq GetAuthUser())) OR
		(IsUserInRole("Organizer") AND user.getRole() neq "Super User" AND user.getRole() neq "Regional Admin") OR
		(IsUserInRole("Site Contact") AND user.getUser_ID() eq GetAuthUser())
	)> --->
	
<cfif IsNumeric(user.getUser_ID())>
	
	<cfscript>
		base = new assets.calgrants.com.Base();
		qUser = userGateway.query(User_ID = user.getUser_ID());
		passbackQueryString = base.passbackToQueryString(passback);
		organizationGateway = new assets.calgrants.com.gateway.OrganizationGateway();
		organizations = organizationGateway.query(regionIDs = IIf(IsUserInRole("Regional Admin"), request.authUser.regionID, ""), Organization_ID = IIf(IsUserInRole("Organizer") OR IsUserInRole("Site Contact"), request.authUser.organizationID, ""));
		storedProcedureGateway = new assets.calgrants.com.gateway.StoredProcedureGateway();
		regions = storedProcedureGateway.call(sp = "getDistinctRegions");
	</cfscript>
	
	<!--- To Do: Add/Edit/Delete rules - legacy.  Delete after review
	<cfif user.getUser_ID() gt 0>
		
		<cfif NOT user.Archived>
			<script type="text/javascript" language="JavaScript">
			<!--
				confirmArchive = function () {
					if (confirm("Are you sure you want to archive this user?")) {
						window.location = "#script_name#?action=archiveUser&userID=#user.getUser_ID()#";
					} else {
						return false;
					}
				}
			//-->
			</script>
		</cfif>
		
	</cfif> --->
	<!--- permissions --->
	<!--- <cfif 	authuser.Role neq "Site Contact" or
			authuser.getUser_ID() eq userID>
		<cfset canSave = true>
	<cfelse>
		<cfset canSave = false>
	</cfif>

	<cfif 	((IsUserInRole("Organizer") and user.Role neq "Super User" and user.Role neq "Regional Admin") or
			(IsUserInRole("Regional Admin") and user.Role neq "Super User") or
			(IsUserInRole("Super User"))) and
			((user.Approved and workshopCount eq 0 and orderCount eq 0 and fundCount eq 0) or
			(NOT user.Approved)) and
			(user.Email neq "dcostopoulos@csac.ca.gov" and user.Email neq "ken@jel.net")>
		<cfset canApprove = true>
	<cfelse>
		<cfset canApprove = false>
	</cfif> --->

	<!--- <cfif 	IsUserInRole("Super User") and userID gt 0 and userID neq authuser.getUser_ID() and workshopCount eq 0 and orderCount eq 0 and fundCount eq 0>
		<cfset canDelete = true>
		<script type="text/javascript">
		<!--
			confirmDelete = function  {
				if (confirm("Are you sure you want to delete this user?")) {
					window.location = "#script_name#?m=userFormDelete&view=#rv#&userID=#userID#&organizationID=#organizationID#";
				}
			}
		// -->
		</script>
	<cfelse>
		<cfset canDelete = false>
	</cfif> --->

	<!--- <cfif 	((IsUserInRole("Super User")) or (IsUserInRole("Regional Admin") and userID eq 0)) and
			(user.Email neq "dcostopoulos@csac.ca.gov" and user.Email neq "ken@jel.net") and
			(workshopCount eq 0 and orderCount eq 0 and fundCount eq 0)>
		<cfset canChangeOrganization = true>
	<cfelse>
		<cfset canChangeOrganization = false>
	</cfif>

	<cfif 	canChangeOrganization or
			(NOT canChangeOrganization and user.Role eq "Site Contact") or
			(NOT canChangeOrganization and user.Role eq "Organizer" and organizerCount eq 0) or
			(NOT canChangeOrganization and userID eq 0)>
		<cfset canChangeRole = true>
		<!--- Mod roles for authUser role --->
		<cfif authuser.Role neq "Super User" or NOT canChangeOrganization>
			<cfset rolesList = ArrayToList(roles)>
			<cfset rolesList = ListDeleteAt(rolesList, ListFindNoCase(rolesList, "Super User"))>
			<cfset rolesList = ListDeleteAt(rolesList, ListFindNoCase(rolesList, "Regional Admin"))>
			<cfset roles = ListToArray(rolesList)>
		</cfif>
	<cfelse>
		<cfset canChangeRole = false>
	</cfif> --->
	<!--- <script type="text/javascript" language="javascript">
	<!--
		toggleRegion = function(selObj) {
			var f = document.getElementById("userForm");
			if (selObj.options[selObj.selectedIndex].value == "Super User") {
				document.getElementById("regionContainer").style.display = "none";
				document.getElementById("regionContainer").style.visibility = "hidden";
			} else if (selObj.options[selObj.selectedIndex].value == "Regional Admin") {
				document.getElementById("regionContainer").style.display = "inline";
				document.getElementById("regionContainer").style.visibility = "visible";
			} else {
				document.getElementById("regionContainer").style.display = "none";
				document.getElementById("regionContainer").style.visibility = "hidden";
			}
		}
		validateForm = function() {
			var f = document.getElementById("userForm");
			var roleVal = f.role.options[f.role.selectedIndex].value;
			var organizationIDVal = "";
			if (f.organizationID.type == "hidden") {
				organizationIDVal = f.organiztionID.value;
			} else {
				organizationIDVal = f.organizationID.options[f.organizationID.selectedIndex].value;
			}
			if (roleVal == "Super User" && organizationIDVal > 0) {
				alert("Invalid User Configuration\n\nOrganization must be set to \"Super User or Regional Admin\" when Role is set to \"Super User\".");
				return false;
			} else if (roleVal == "Regional Admin" && organizationIDVal > 0) {
				alert("Invalid User Configuration\n\nOrganization must be set to \"Super User or Regional Admin\" when Role is set to \"Regional Admin\".");
				return false;
			} else if ((roleVal == "Organizer" || roleVal == "Site Contact") && organizationIDVal == 0) {
				alert("Invalid User Configuration\n\nOrganization may not be set to \"Super User or Regional Admin\" when Role is set to \"" + roleVal + "\".");
				return false;
			} else {
				return true;
			}
		}
	// -->
	</script> --->
	
	<script type="text/javascript" language="javascript">
	<!--
		<cfoutput>
			var userID = #user.getUser_ID()#;
			var organizationID = #user.getOrganization_ID()#;
			var role = "#user.getRole()#";
			var regionIDs = #user.getRegion_IDs()#;
			var organizations = new kendo.data.DataSource();
			organizations.data(#SerializeJSON(base.QueryToStruct(organizations), false)#);
			<cfif IsUserInRole("Super User")>
				organizations.insert(0, {organization: "No organization", address: "Select for Super User or Regional Admin", city: "", zip_code: "", organization_id: 0});
			</cfif>
			var regions =  new kendo.data.DataSource();
			regions.data(#SerializeJSON(base.QueryToStruct(regions), false)#);
			regions.insert(0, {region: "Select...", region_id: 0});
			var passbackQueryString = "#passbackQueryString#";
			var archiveUrl = "?action=archiveUser&view=#returnView#&User_ID=#user.getUser_ID()#";
		</cfoutput>	
		
		var roles = new kendo.data.DataSource();
		var adminRoles = [
			{role: "Super User", description: "Super Users have administrative access statewide"},
			{role: "Regional Admin", description: "Regional Admins have managerial access within their region"}
		];
		var organizationRoles = [
			{role: "Organizer", description: "Organizers have managerial access within their organization"},
			{role: "Site Contact", description: "Site Contacts have read-only access to assigned workshops"}
		];
		if (userID == 0 || role == "Organizer" || role == "Site Contact") {
			roles.data(organizationRoles);
		} else {
			roles.data(adminRoles);
		}		
		var validate = function() {
			var errors = "";
			var valid = true;
			if (organizationDropdown.value() == 0) {
				if (roleDropdown.value() == "Regional Admin") {
					if (regionDropdown.value() == 0) {
						valid = false;
						errors += "Region is required for Regional Admin\n";
					}
				} else if (roleDropdown.value() == "Super User") {
					regionDropdown.value(0);
				} else {
					valid = false;
					errors += "Data inconsistency error in user.  Please report this error to Cash for College.\n";	
				}
			} else {
				if (roleDropdown.value() == "Organizer" || roleDropdown.value() == "Site Contact") {
					regionDropdown.value(0);
				} else {
					valid = false;
					errors += "Data inconsistency error in user.  Please report this error to Cash for College.\n";
				}
			}
			if (!valid) {
				alert(errors);
			}
			return valid;				
		}
		var refreshOrganization = function() {
			if (organizationDropdown.value() == 0) {
				roles.data(adminRoles);
				roleDropdown.refresh();
				roleDropdown.select(0);
			} else {
				roles.data(organizationRoles);
				roleDropdown.refresh();
				roleDropdown.select(0);
			}
			refreshRole();
		}
		var refreshRole = function() {
			if (roleDropdown.value() == "Regional Admin") {
				$("#regionIDsContainer").show();
				regionDropdown.select(0);
			} else {
				$("#regionIDsContainer").hide();
				regionDropdown.select(0);
			}
		}
		var confirmArchive = function() {
			if (confirm("Are you sure you want to archive this user?\n\nArchiving does not delete the user and the account will still be associated with existing workshops, orders, etc.\n\nAccounts can be unarchived at any time from the users list.")) {
				if (passbackQueryString.length) {
					window.location = archiveUrl + "&" + passbackQueryString;
				} else {
					window.location = archiveUrl;
				}
			}
		}
		$(function() {	
			organizationDropdown = $("#Organization_ID").kendoDropDownList({
				dataTextField: "organization",
				dataValueField: "organization_id",
				dataSource: organizations,
				template: 	'<strong>${organization}</strong><br>' +
							'${address}' +
							' # if (data.city.length > 0) { # ' +
							'<br>${city}, CA ${zip_code}' +
							' # } # ',
				change: function() {
					refreshOrganization();
				}
			}).data("kendoDropDownList");
			if (userID == 0) {
				organizationDropdown.select(0);
			} else {
				organizationDropdown.value(organizationID);
			}
			regionDropdown = $("#Region_IDs").kendoDropDownList({
				dataTextField: "region",
				dataValueField: "region_id",
				dataSource: regions,
				template: 	' # if (data.region_id !== 0) { # ' +
							'${region_id} - ' +
							' # } # ' +
							'${region}'
			}).data("kendoDropDownList");
			if (regionIDs == 0) {
				regionDropdown.select(0);
			} else {
			regionDropdown.value(regionIDs);
			}
			roleDropdown = $("#Role").kendoDropDownList({
				dataTextField: "role",
				dataValueField: "role",
				dataSource: roles,
				template: 	'<strong>${role}</strong><br>' +
							'${description}',
				change: function() {
					refreshRole();
				}
			}).data("kendoDropDownList");
			roleDropdown.value(role);
			$("#userModal").modal();
			resizeModal("userModal");
		})
	//-->
	</script>
	
	<cfoutput>
	
		<cfform name="userForm" id="userForm" action="#script_name#" method="post" onsubmit="return validate();">
			<cfinput type="hidden" name="action" value="saveUser" />
			<cfinput type="hidden" name="view" value="#returnView#" />
			<cfinput type="hidden" name="User_ID" value="#user.getUser_ID()#" />
			<cfif IsDefined("passback")>
				<cfloop index="keyValue" list="#passback#" delimiters=";">
					<cfinput type="hidden" name="#ListFirst(keyValue)#" value="#ListLast(keyValue)#" />
				</cfloop>
			</cfif>

			<div id="userModal" class="modal modal-fullscreen" data-backdrop="static">
				<div class="modal-header">
					<h3>User</h3>
				</div>
				<div class="modal-body">
					<div class="container-fluid">
						<div class="row-fluid">
							<div class="span4">
								<cfif NOT IsUserInRole("Site Contact")>
									<cfif user.getArchived()>
										<div class="text-control clearfix">
											<label class="required">Status</label>
											Archived
										</div>
									<cfelse>
										<div class="clearfix">
											<label class="required">Status</label>
											<cfselect name="Approved" required="yes" message="Status is required" class="span12">
												<option value="0"<cfif user.getApproved() eq 0> selected</cfif>>Not approved</option>
												<option value="1"<cfif user.getApproved() eq 1> selected</cfif>>Approved</option>
											</cfselect>
										</div>
									</cfif>
								<cfelse>
									<div class="text-control clearfix">
										<label>Status</label>
										<cfif user.getUser_ID() eq 0>
											New
										<cfelseif user.getArchived()>
											Archived
										<cfelseif user.getApproved()>
											Approved
										<cfelse>
											Pending Approval
										</cfif>
									</div>
								</cfif>
								<div class="kendo-control clearfix">
									<label class="required">Organization</label>
									<cfselect name="Organization_ID" required="yes" message="Organization is required" class="span12" style="margin: 0;"></cfselect>
								</div>
								<div class="kendo-control clearfix">
									<label class="required">Role</label>
									<cfselect name="Role" required="yes" message="Role is required" class="span12" style="margin: 0;"></cfselect>
								</div>
								<div id="regionIDsContainer" class="kendo-control clearfix"<cfif user.getRole() neq "Regional Admin"> style="display: none;"</cfif>>
									<label class="required">Region</label>
									<cfselect name="Region_IDs" class="span12" style="margin: 0;"></cfselect>
								</div>
								<!--- <cfif user.getUser_ID() gt 0>
									<div class="text-control clearfix">
										<label>ID</label>
										#user.getUser_ID()#
									</div>
									<div class="text-control clearfix">
										<label>Date Created</label>
										#DateFormat(user.getDate_Created(), "mmmm d yyyy")# @ #TimeFormat(user.getDate_Created(), "h:mmtt")#
									</div>
								</cfif> --->
							</div>
							<div class="span4">
								<div class="clearfix">
									<label class="required">First Name</label>
									<cfinput type="text" name="First_Name" value="#user.getFirst_Name()#" required="yes" message="First Name is required" maxlength="50" class="span12">
								</div>
								<div class="clearfix">
									<label class="required">Last Name</label>
									<cfinput type="text" name="Last_Name" value="#user.getLast_Name()#" required="yes" message="Last Name is required" maxlength="50" class="span12">
								</div>
								<div class="clearfix">
									<label>Title</label>
									<cfinput type="text" name="Title" value="#user.getTitle()#" required="no" maxlength="100" class="span12">
								</div>
								<div class="clearfix">
									<label class="required">E-mail</label>
									<cfinput type="text" name="Email" value="#user.getEmail()#" required="yes" message="E-mail is required and must be a valid e-mail address" validate="email" maxlength="100" class="span12">
								</div>
								<div class="clearfix">
									<div class="row-fluid">
										<div class="span9">
											<label for="Phone" class="required">Phone</label>
											<cfinput type="text" id="Phone" name="Phone" value="#user.getPhone()#" class="span12" required="yes" validate="telephone" message="Phone is required and must be a valid phone number" placeholder="######-######-########">
										</div>
										<div class="span3">
											<label for="Extension">Extension</label>
											<cfinput type="text" id="Extension" name="Extension" value="#user.getExtension()#" class="span12">
										</div>
									</div>
								</div>
								<cfif IsUserInRole("Super User")>
									<div class="clearfix">
										<label class="required">Password</label>
										<cfinput type="text" name="Password" value="#user.getPassword()#" required="yes" message="Password is required" maxlength="50" class="span12">
									</div>
								<cfelseif IsUserInRole("Regional Admin") OR IsUserInRole("Organizer") OR (IsUserInRole("Site Contact") AND user.getUser_ID() eq GetAuthUser())>
									<div class="clearfix">
										<label class="required">Password</label>
										<cfinput type="password" name="Password" value="#user.getPassword()#" required="yes" message="Password is required" maxlength="50" class="span12">
									</div>
								</cfif>
							</div>
							<!--- <div class="span4">
								<cfif (IsUserInRole("Super User") OR IsUserInRole("Regional Admin")) AND user.getUser_ID() gt 0>
								
									<!--- <cfset organizationID = user.getOrganization_ID() />
									<cfset userID = user.getUser_ID() /> --->
							
									<!--- <div class="accordion" id="organizationAccordian">
										<div class="accordion-group">
											<div class="accordion-heading">
												<a class="accordion-toggle" data-toggle="collapse" data-parent="##organizationAccordian" href="##panel1">Workshops</a>
											</div>
											<div id="panel1" class="accordion-body collapse">
												<div class="accordion-inner">
													<cfinclude template="#request.pathToUI#/lists/workshops.cfm">
												</div>
											</div>
										</div>
										<div class="accordion-group">
											<div class="accordion-heading">
												<a class="accordion-toggle" data-toggle="collapse" data-parent="##organizationAccordian" href="##panel2">Orders</a>
											</div>
											<div id="panel2" class="accordion-body collapse">
												<div class="accordion-inner">
													<cfinclude template="#request.pathToUI#/lists/orders.cfm">
												</div>
											</div>
										</div>
									</div> --->
								
								</cfif>
							</div> --->
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<a href="?view=#returnView#&#passbackQueryString#" class="btn btn-success">Cancel</a>
					<cfif NOT IsUserInRole("Site Contact")>
						<cfif user.getUser_ID() gt 0 AND user.getArchived() eq 0>
							<a href="" class="btn btn-success" onclick="confirmArchive(); return false;">Archive</a>
						<cfelseif user.getUser_ID() gt 0 AND user.getArchived() eq 1>
							<a href="?action=unarchiveUser&view=#returnView#&User_ID=#user.getUser_ID()#&#passbackQueryString#" class="btn btn-success">Unarchive</a>
						</cfif>
					</cfif>
					<button type="submit" name="saveButton" class="btn btn-success">Save</button>
				</div>
			</div>

		</cfform>
	
	</cfoutput>

<cfelse>

	<div class="alert alert-info notFound">User not found</div>

</cfif>